﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using CloudTaobao.Util;
using System.Text;
using System.Windows.Media.Imaging;

namespace CloudTaobao
{
    public partial class MessagePage : PhoneApplicationPage
    {
        string uid = "";
        string itemId = "";
        Find fd = new Find();
        WangwangTool wwtool = new WangwangTool();

        public MessagePage()
        {
            InitializeComponent();

            fd.messageList.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(messageList_CollectionChanged);
            fd.startLoadingEvent += new StartLoadingEventHandler(fd_startLoadingEvent);
            fd.endLoadingEvent += new EndLoadingEventHandler(fd_endLoadingEvent);
            MessageList.ItemsSource = fd.messageList;
        }

        void messageList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (MessageList.Items.Count == 0 || MessageList.Items.Count == 1)
                return;
            MessageList.ScrollIntoView(MessageList.Items[MessageList.Items.Count-1]);
            MessageList.UpdateLayout();
        }

        void fd_endLoadingEvent()
        {
            LoadingBar.IsIndeterminate = false;
            LoadingBar.Visibility = Visibility.Collapsed;
        }

        void fd_startLoadingEvent(object source, StartLoadingEventArgs args)
        {
            LoadingBar.IsIndeterminate = true;
            LoadingBar.Visibility = Visibility.Visible;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            uid = this.NavigationContext.QueryString["uid"];
            itemId = this.NavigationContext.QueryString["itemId"];
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            App app = Application.Current as App;
            if (!app.sessionInfo.ContainsKey("top_session") || app.sessionInfo["top_session"] == "" || app.sessionInfo["nick"] == "")
            {
                if (MessageBox.Show("抱歉^_^您需要登录才能使用此功能,是否转向登录页面？", "缺少登录信息",
                    MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    NavigationService.Navigate(new Uri("/LoginPage.xaml", UriKind.Relative));
                }
                else
                {
                    NavigationService.GoBack();
                }
                return;
            }

            fd.showMessagePage = 1;
            if (uid.StartsWith("cntaobao"))
                PageTitle.Text = uid.Substring(8);
            else
                PageTitle.Text = uid;

            try
            {
                if (uid.StartsWith("cntaobao"))
                    fd.GetMessageList(uid);
                else
                    fd.GetMessageList("cntaobao" + uid);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Send_Click(object sender, RoutedEventArgs e)
        {
            if(MessageContent.Text=="")
                return;
            if (ValidPanel.Visibility == Visibility.Collapsed)
            {
                initSession();
            }
            else 
            {
                if (ValidCode.Text == "")
                    return;
                wwtool.sendMsg(ValidCode.Text);
                ValidCode.Text = "";
                ValidPanel.Visibility = Visibility.Collapsed;
                addToMessageList();
            }
        }

        private void addToMessageList()
        {
            //在用户界面上新加一条消息
            WangMessage wm = new WangMessage();
            wm.direction = "0";
            wm.content = MessageContent.Text;
            wm.time = DateTime.Now.Date.ToString("yyyy-MM-dd hh:mm:ss");
            fd.messageList.Add(wm);
            //去除文本框中文字
            MessageContent.Text = "";
        }

        private void initSession()
        {
            string url = "http://wangwang.wap.taobao.com/ww/wap_ww_dialog.htm?";
            if (itemId != "") 
            {
                url += "itemNumId=";
                url += itemId;
            }
            url += "&to_user=";
            url += Convert.ToBase64String(Encoding.UTF8.GetBytes(uid));
            hiddenWeb.Navigate(new Uri(url));
        }

        private void hiddenWeb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            if (e.Uri.AbsolutePath.Equals("/ww/wap_ww_dialog.htm"))
            {
                string html = hiddenWeb.SaveToString();
                string validUrl = wwtool.send(html, uid, MessageContent.Text,itemId);

                if (validUrl != "") 
                {
                    ValidImg.Source = new BitmapImage(new Uri(validUrl, UriKind.RelativeOrAbsolute));
                    ValidPanel.Visibility = Visibility.Visible;
                    return;
                }

                addToMessageList();
            }
        }

        private void refresh_Click(object sender, EventArgs e)
        {
            try
            {
                fd.GetMessageList(uid);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}